﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EAppointment.Models
{
    public class JsonpResult : JsonResult
    {

        object data = null;

        public JsonpResult()
        {
            this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }

        public JsonpResult(object data)
        {
            this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            this.data = data;

        }

        public override void ExecuteResult(ControllerContext controllerContext)
        {

            if (controllerContext != null)
            {

                HttpResponseBase Response = controllerContext.HttpContext.Response;

                HttpRequestBase Request = controllerContext.HttpContext.Request;



                string callbackfunction = Request["callback"];

                //if (string.IsNullOrEmpty(callbackfunction))
                //{

                //    throw new Exception("Callback function name must be provided in the request!");

                //}

                Response.ContentType = "application/json; charset=utf-8";

                if (data != null)
                {
                    if (string.IsNullOrWhiteSpace(callbackfunction))
                        Response.Write(JsonConvert.SerializeObject(data));
                    else
                        Response.Write(string.Format("{0}({1})", callbackfunction, JsonConvert.SerializeObject(data)));
                }

            }

        }

    }
}